package com.imageim.yimirror.common.ui;

import android.content.Context;
import android.util.AttributeSet;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Scroller;
import android.widget.TextView;
import com.imageim.yimirror.R;
import com.imageim.yimirror.common.ui.tip.TipUtil;
import com.imageim.yimirror.common.util.DensityUtil;
import com.imageim.yimirror.common.util.LogUtil;

/**
 * 折叠视图
 * Created by Bruce.Zhou on 2018/06/26.
 */

public class FoldingActionView2 extends RelativeLayout implements GestureDetector.OnGestureListener {

    private GestureDetector gestureDetector;
    private int measuredWidth;
    private int measuredHeight;
    private Scroller scroller;

    public FoldingActionView2(Context context) {
        super(context);
        init();
    }

    public FoldingActionView2(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public FoldingActionView2(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private float prevScrollY;
    private boolean isFolded = true;

    private void init() {
        initView();
        setEnabled(true);
        setClickable(true);
        gestureDetector = new GestureDetector(getContext(), this);
        panelHead.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_UP:

                        break;
                    default:
                        break;
                }
                gestureDetector.onTouchEvent(event);
                return FoldingActionView2.super.onTouchEvent(event);
            }
        });
        scroller = new Scroller(getContext());
    }

    private static int FOLDING_DISNTANCE;
    private static final int MSG_MOVE_DOWN = 1;
    private static final int MSG_MOVE_UP = 2;
    private TextView tvTitle;
    private ViewGroup panelHead;
    private ViewGroup panelContent;
    private LinearLayout rootView;
//    private Handler handler = new Handler() {
//        @Override
//        public void handleMessage(Message msg) {
//            switch (msg.what) {
//                case MSG_MOVE_DOWN:
//
//                    break;
//                case MSG_MOVE_UP:
//                    break;
//            }
//        }
//    };

    private void initView() {
        FOLDING_DISNTANCE = DensityUtil.dip2px(getContext(), 100);
        View root = View.inflate(getContext(), R.layout.layout_main_page, this);
        rootView = root.findViewById(R.id.root);
        panelContent = root.findViewById(R.id.panel_content);
        panelHead = root.findViewById(R.id.panel_head);
        tvTitle = root.findViewById(R.id.tv_title);
        tvTitle.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isFolded) {
                    TipUtil.show("dfjdif");
                    moveDown();
                } else {
                    moveUp();
                }
            }
        });
        rootView.scrollTo(0, FOLDING_DISNTANCE);
        rootView.requestLayout();
        rootView.invalidate();
        panelContent.setLayoutParams(new LinearLayout.LayoutParams(1080, 1920));
    }

    public void moveDown() {
        if (rootView.getScrollY() > 0) {
            rootView.scrollTo(0, rootView.getScrollY() - 2);
            rootView.postDelayed(new Runnable() {
                @Override
                public void run() {
                    moveDown();
                }
            }, 1);
        } else {
            rootView.scrollTo(0, 0);
            isFolded = false;
        }
    }

    public void moveUp() {
        if (rootView.getScrollY() < FOLDING_DISNTANCE) {
            rootView.scrollTo(0, rootView.getScrollY() + 2);
            rootView.postDelayed(new Runnable() {
                @Override
                public void run() {
                    moveUp();
                }
            }, 1);
        } else {
            rootView.scrollTo(0, FOLDING_DISNTANCE);
            isFolded = true;
        }
    }

    protected void beginScroll(int dx, int dy, int duration) {
        scroller.startScroll(scroller.getFinalX(), scroller.getFinalY(), dx, dy, duration);
        invalidate();
    }

    protected void reset(int x, int y) {
        int dx = x - scroller.getFinalX();
        int dy = y - scroller.getFinalY();
        beginScroll(dx, dy, 500);
    }

    @Override
    public void computeScroll() {
        if (scroller.computeScrollOffset()) {
            scrollTo(scroller.getCurrX(), scroller.getCurrY());
            panelHead.setLayoutParams(new LinearLayout.LayoutParams(1080
                    , DensityUtil.dip2px(getContext(), 200)
            ));
            invalidate();
        }
    }

    private static int MAX_TRICKER_DISTANCE = 500;

    public interface MyGestureListener {
        void onFlingLeft();

        void onFlingRight();

        void onFlingUp();

        void onFlingDown();

        void onTouchDown();

        void onTouchUp(float rate, Direction direction);

        void onScroll(float rate, Direction direction); // rate 0~1 1表示内容不反弹回原点的临界值
    }

    public enum Direction {
        NONE, LEFT, RIGHT, UP, DOWN
    }

    public static class MyGestureListenerAdapter implements MyGestureListener {
        @Override
        public void onFlingLeft() {
        }

        @Override
        public void onFlingRight() {
        }

        @Override
        public void onFlingUp() {
        }

        @Override
        public void onFlingDown() {
        }

        @Override
        public void onTouchDown() {
        }

        @Override
        public void onTouchUp(float rate, Direction direction) {
        }

        @Override
        public void onScroll(float rate, Direction direction) {
        }
    }

    private MyGestureListener myGestureListener;

    public void setMyGestureListener(MyGestureListener listener) {
        myGestureListener = listener;
    }

    @Override
    public boolean onDown(MotionEvent e) {
        LogUtil.d("gesture", "touch down");
        if (myGestureListener != null) {
            myGestureListener.onTouchDown();
        }
        return true;
    }

    @Override
    public void onShowPress(MotionEvent e) {
        LogUtil.d("gesture", "onShowPress..." + e.getAction());
    }

    @Override
    public boolean onSingleTapUp(MotionEvent e) {
        return false;
    }

    @Override
    public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
        return false;
    }

    @Override
    public void onLongPress(MotionEvent e) {

    }

    private static final int MIN_SPEED = 3000;
    private static final int MIN_SPEED_TOLERONCE = 3000;

    @Override
    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
        if (myGestureListener != null) {
            if (velocityX > MIN_SPEED && Math.abs(velocityY) < MIN_SPEED_TOLERONCE) {
                myGestureListener.onFlingRight();
//                LogUtil.d("gesture", "fling right");
            } else if (velocityX < -MIN_SPEED && Math.abs(velocityY) < MIN_SPEED_TOLERONCE) {
                myGestureListener.onFlingLeft();
//                LogUtil.d("gesture", "fling left");
            } else if (velocityY > MIN_SPEED && Math.abs(velocityX) < MIN_SPEED_TOLERONCE) {
                myGestureListener.onFlingDown();
//                LogUtil.d("gesture", "fling down");
            } else if (velocityY < -MIN_SPEED && Math.abs(velocityX) < MIN_SPEED_TOLERONCE) {
                myGestureListener.onFlingUp();
//                LogUtil.d("gesture", "fling up");
            }
//            LogUtil.d("gesture", "onFling " + velocityX + ", " + velocityY);
//            Log.d("gesture", "fling...");
        }
        return false;
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        measuredWidth = MeasureSpec.getSize(widthMeasureSpec);
        measuredHeight = MeasureSpec.getSize(heightMeasureSpec);
        MAX_TRICKER_DISTANCE = (int) (measuredWidth / 5.0f);
        LogUtil.d("gesture", "w=" + measuredWidth + ", h=" + measuredHeight);
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        super.onLayout(changed, l, t, r, b);
    }
}
